package com.base.controller.wx_developers_api;

import com.base.helper.WebHelper;
import com.base.po.param.NetState;
import com.base.po.voip.Subscribers;
import com.base.po.voip.SubscribersExpand;
import com.base.po.voip.UsersConfig;
import com.base.po.wx.WXJsCode2Session;
import com.base.service.SubscribersExpandService;
import com.base.service.SubscribersService;
import com.base.service.UsersConfigService;
import com.base.service.UsersService;
import net.sf.json.JSONObject;
import org.apache.commons.collections.map.HashedMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;


/**
 * 微信接口
 *
 * @author K.
 */
@Controller
@RequestMapping("/weixin")
public class Wx_AuthController {
    @Autowired
    private UsersService usersService;
    @Autowired
    private SubscribersService subscribersService;
    @Autowired
    private UsersConfigService usersConfigService;
    @Autowired
    private SubscribersExpandService subscribersExpandService;

    /**
     * 微信 - 用户小程序授权
     */
    @RequestMapping(value = "/authAuthorize", method = {RequestMethod.POST, RequestMethod.GET})
    public @ResponseBody
    NetState authorize(HttpServletRequest request, String parentId, String code) {
        NetState netState = new NetState();

        if (parentId == null || parentId.equals("") || code == null || code.equals("")){
            netState.setErrorCode(NetState.PARAMS_ERROR);
            netState.setData("参数异常");
            return netState;
        }

        // 配置
        UsersConfig usersConfig = null;
        String appId = null;
        String secret = null;
        try {
            usersConfig = usersConfigService.selectByParentId(parentId);
            // 小程序appId
            appId = usersConfig.getWxDevelopersAppid();
            // 小程序appSecret
            secret = usersConfig.getWxDevelopersAppsecret();
        }catch (Exception e){
            netState.setErrorCode(NetState.NODATA);
            netState.setData("数据异常");
            return netState;
        }

        try {
            Map<String, Object> sessionKeyMap = getSessionKey(appId, secret, code);
            String openId = (String)sessionKeyMap.get("openId");
            String sessionKey = (String)sessionKeyMap.get("sessionKey");
            if (sessionKey != null && !sessionKey.equals("") && openId != null && !openId.equals("")){
                SubscribersExpand expand = subscribersExpandService.selectByDevelopersOpenId(openId);
                if (expand != null){
                    sessionKeyMap.put("isBinding", true);
                }else {
                    sessionKeyMap.put("isBinding", false);
                }
                sessionKeyMap.put("parentId", usersConfig.getId());
                netState.setErrorCode(NetState.SUCCESS_CONN);
                netState.setData("授权成功");
                netState.setJson(sessionKeyMap);
            }else {
                netState.setErrorCode(NetState.ERROR_OPERATE);
                netState.setData("授权失败,无效sessionKey");
            }
        }catch (Exception e){
            netState.setErrorCode(NetState.SYSTEM_ERROR);
            netState.setData("授权异常,无效code");
        }
        return netState;
    }

    public Map<String, Object> getSessionKey(String appId, String appSecret, String code){
        Map<String, Object> map = new HashedMap();

        String sessionUrl = "https://api.weixin.qq.com/sns/jscode2session?appid=" + appId + "&secret=" + appSecret + "&js_code=" + code + "&grant_type=authorization_code";
        try {
            String result = WebHelper.PostData(sessionUrl, null, null, null);
            WXJsCode2Session session = (WXJsCode2Session)JSONObject.toBean(JSONObject.fromObject(result), WXJsCode2Session.class);
            map.put("openId", session.getOpenid());
            map.put("sessionKey", session.getSession_key());
        }catch (Exception e){
            e.printStackTrace();
            map = null;
        }

        return map;
    }

    /**
     * 微信 - 用户小程序绑定用户信息
     */
    @RequestMapping(value = "/authBinding", method = {RequestMethod.POST, RequestMethod.GET})
    public @ResponseBody
    NetState authBinding(HttpServletRequest request, String parentId, String mobile, String openId) {
        NetState netState = new NetState();

        if (parentId == null || parentId.equals("") || mobile == null || mobile.equals("") || openId == null || openId.equals("")){
            netState.setErrorCode(NetState.PARAMS_ERROR);
            netState.setData("参数异常");
            return netState;
        }

        List<Subscribers> subscribersList = subscribersService.selectBySub(mobile, parentId);
        SubscribersExpand expand = subscribersExpandService.selectByDevelopersOpenId(openId);
        if (expand != null && expand.getUserid() != null){
            netState.setErrorCode(NetState.DATA_RE);
            netState.setData("请勿重复绑定");
        }else {
            Subscribers subscribers = subscribersList.get(0);
            expand = new SubscribersExpand();
            expand.setUserid(subscribers.getId());
            expand.setWxdevelopersopenid(openId);
            int code = subscribersExpandService.insertSelective(expand);
            if (code == 1){
                netState.setErrorCode(NetState.SUCCESS_CONN);
                netState.setData("绑定成功");
            }else {
                netState.setErrorCode(NetState.ERROR_OPERATE);
                netState.setData("绑定失败");
            }
        }

        return netState;
    }
}
